package com.lzc.tlmall.tlmallauthservice.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lzc.common.utils.HttpUtils;
import com.lzc.common.utils.R;
import com.lzc.common.vo.OauthUser;
import com.lzc.common.constant.OauthConstant;
import com.lzc.tlmall.tlmallauthservice.feign.UserFeignService;
import com.lzc.common.vo.MemberEntityVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lzc
 * @create 2020-10-14 20:34
 */
@Controller
public class Oauth2Controller {

    @Autowired
    private UserFeignService userFeignService;

    /**
     * 微博社交登录
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String weiboLogin(@RequestParam("code")String code, HttpSession session)throws Exception{
        /**
         * String host, String path, String method,
         * 			Map<String, String> headers,
         * 			Map<String, String> querys,
         * 			Map<String, String> bodys
         */
        Map<String,String > header=new HashMap<>();
        Map<String,String > query=new HashMap<>();
        Map<String,String > body=new HashMap<>();
        body.put("client_id","4014627172");
        body.put("client_secret","b499f4332e14729a380ee38a31ae7ad9");
        body.put("grant_type","authorization_code");
        body.put("redirect_uri","http://www.auth.tlmail.com/oauth2.0/weibo/success");
        body.put("code",code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "POST", header, query, body);
        if(response.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(response.getEntity());
            System.out.println(json);
            OauthUser oauthUser = JSON.parseObject(json, OauthUser.class);
            R r = userFeignService.oauthLogin(oauthUser);
            if(r.getCode()==0){
                MemberEntityVo memberEntityVo = r.getData("data", new TypeReference<MemberEntityVo>() {
                });
                session.setAttribute(OauthConstant.OAUTH_LOGINUSER,memberEntityVo);
                return "redirect:http://www.tlmail.com";
            }else {
                return "redirect:http://www.auth.tlmail.com/login.html";
            }

        }else {
            return "redirect:http://www.auth.tlmail.com/login.html";
        }



    }
}
